package com.zbkj.crmeb.store.service.impl;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.constants.Constants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.utils.jackyun.JackyunOpenHttpUtils;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.express.model.Express;
import com.zbkj.crmeb.express.service.ExpressService;
import com.zbkj.crmeb.order.request.JackyunTradeRequest;
import com.zbkj.crmeb.order.request.JkyTradeResDTO;
import com.zbkj.crmeb.order.request.JkyTradeResDTO.DataResult;
import com.zbkj.crmeb.order.request.JkyTradeResDTO.Trade;
import com.zbkj.crmeb.store.model.OrderInfoDelivery;
import com.zbkj.crmeb.store.model.PurchaseGoods;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.request.StoreOrderSendRequest;
import com.zbkj.crmeb.store.service.JkyTradeService;
import com.zbkj.crmeb.store.service.OrderInfoDeliveryService;
import com.zbkj.crmeb.store.service.PurchaseGoodsService;
import com.zbkj.crmeb.store.service.StoreOrderInfoService;
import com.zbkj.crmeb.store.service.StoreOrderService;

import lombok.extern.slf4j.Slf4j;

/**
 * 同步吉客云物流数据
 * @author daigb
 * @date:  2022-04-11 16:44
 */
@Slf4j
@Service
public class JkyTradeServiceImpl implements JkyTradeService {
    @Autowired
    StoreOrderService storeOrderService;
    @Autowired
    StoreOrderInfoService storeOrderInfoService;
    @Autowired
    PurchaseGoodsService purchaseGoodsService;
    @Autowired
    OrderInfoDeliveryService orderInfoDeliveryService;
    @Autowired
    ExpressService expressService;

    private static Map<String, Integer> expressMap = new HashMap<>();
    static {
    	expressMap.put("德邦", 288);
    	expressMap.put("京东", 134);
    	expressMap.put("圆通", 243);
    	expressMap.put("UPS国际", 287);
    	expressMap.put("顺丰陆运", 188);
    	expressMap.put("s008", 273);
    	expressMap.put("百世", 291);
    	expressMap.put("联邦", 275);
    	expressMap.put("DHL", 186);
    	expressMap.put("国际", 287);
    	expressMap.put("ETK", 31);
    	expressMap.put("BC申通", 266);
    	expressMap.put("顺丰快递", 188);
    	expressMap.put("default", 31);
    }
    
	@Override
	public void tradeFullinfoget() {
		// 查询所有未收货的吉客云订单
		List<StoreOrder> orders = storeOrderService.list(Wrappers.<StoreOrder>lambdaQuery()
				.in(StoreOrder :: getStatus, Arrays.asList(-3, -1, 1, 2, 6))
				.eq(StoreOrder :: getPushJkyStatus, 1)
				);
		List<Integer> ids = orders.stream().map(obj -> obj.getId()).collect(Collectors.toList());
		// 根据订单查询详情
		List<StoreOrderInfo> infos = storeOrderInfoService.list(Wrappers.<StoreOrderInfo>lambdaQuery()
				.in(StoreOrderInfo :: getStatus, Arrays.asList(-3, -1, 1, 2, 6))
				.in(StoreOrderInfo :: getOrderId, ids)
//				.eq(StoreOrderInfo :: getId, 7021)
				);
		log.info("--------------- 查询诚品商品订单物流信息, 总数据: {} ---------------", infos.size());
		for(StoreOrderInfo info : infos) {
			log.info("--------------- 开始查询订单: {} 物流信息 ---------------", info.getOrderId());
			// 查询对应的采购商品信息
			List<PurchaseGoods> purchaseGoods = purchaseGoodsService.list(Wrappers.<PurchaseGoods>lambdaQuery()
					.eq(PurchaseGoods :: getStoreOrderInfoId, info.getId())
					);
			getTrade(purchaseGoods, info);
		}
		log.info("--------------- 查询诚品商品订单物流信息结束 ---------------");
	}
	
	/**
	 * 查询对应物流信息
	 * @author daigb
	 * @date:  2022-04-11 14:39
	 */
	private void getTrade(List<PurchaseGoods> purchaseGoods, StoreOrderInfo info) {
		List<String> jkyOrderNo = purchaseGoods.stream().map(obj -> obj.getChannelOrderSn()).collect(Collectors.toList());
		try {
			JkyTradeResDTO jkyTradeResDTO = this.getJkyTradeFullinfoget(jkyOrderNo);
			if(200 != jkyTradeResDTO.getCode()) {
				log.info("--------------- 查询诚品商品订单物流信息失败, 订单号: {}, 失败信息: {} ---------------", info.getId(), jkyTradeResDTO.getMsg());
				return;
			}
			
			// 查询对应物流
			DataResult result = jkyTradeResDTO.getResult().getDataResult();
			List<Trade> trades = result.getTrades();
			for(Trade trade : trades) {
				String postId = trade.getMainPostid();
				String logisticName = trade.getLogisticName();
				String tradeNo = trade.getTradeNo();
				// 查询系统物流单号
				if(StringUtils.isNotBlank(postId)) {
					int deliveryCount = orderInfoDeliveryService.count(Wrappers.<OrderInfoDelivery>lambdaQuery()
							.eq(OrderInfoDelivery :: getOrderInfoId, info.getId())
							.eq(OrderInfoDelivery :: getDeliveryNumber, postId)
							);
					// 不存在则新增
					if(0 >= deliveryCount) {
						int expressId = null == expressMap.get(logisticName) ? expressMap.get("default") : expressMap.get(logisticName);
						// 判断订单状态(代发货和待确认)
						if(Constants.ORDER_STATUS_H5_NOT_SHIPPED == info.getStatus() || Constants.ORDER_STATUS_H5_CONFIRM == info.getStatus()) {
							StoreOrderSendRequest request = new StoreOrderSendRequest();
							request.setType("1");
							request.setLogisticsType(0);
							request.setExpressId(expressId + "");
							request.setExpressCode(postId);
							request.setId(info.getOrderId());
							request.setOrderInfoId(info.getId());
							request.setName("物流快递");
							request.setLevel(1);
							request.setChannel(4);
							request.setIsConfirm(true);
							
							storeOrderService.send(request);
						} else {
						    Express express = expressService.info(expressId);
							OrderInfoDelivery orderInfoDelivery = new OrderInfoDelivery();
							orderInfoDelivery.setOrderInfoId(info.getId());
							orderInfoDelivery.setExpressId(express.getId());
							orderInfoDelivery.setDeliveryCode(express.getCode());
							orderInfoDelivery.setDeliveryCompany(express.getName());
							orderInfoDelivery.setDeliveryNumber(postId);
							orderInfoDelivery.setName("物流快递");
							orderInfoDelivery.setChannel(4);
							orderInfoDeliveryService.save(orderInfoDelivery);
						}
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
    
    /**
     * 吉客云物流查询
     * @author daigb
     * @return 
     * @date:  2022-04-11 10:20
     */
    public JkyTradeResDTO getJkyTradeFullinfoget(List<String> jkyOrderNo) throws Exception {
    	JkyTradeResDTO JkyTradeResDTO = null;
    	try {
    		JackyunTradeRequest jackyunTradeRequest = new JackyunTradeRequest();
    		jackyunTradeRequest.setPageSize(200);
    		jackyunTradeRequest.setTradeNo(String.join(",", jkyOrderNo));
    		String result = JackyunOpenHttpUtils.post("oms.trade.fullinfoget", "v1.0", jackyunTradeRequest);
    		ObjectMapper mapper = new ObjectMapper();
    		JkyTradeResDTO = mapper.readValue(result, JkyTradeResDTO.class);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	
    	return JkyTradeResDTO;
    }
    
}
